﻿using HookupAppForm.Draw.Models;
using HookupAppForm.Dto;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Configuration;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace HookupAppForm.Draw
{
    /// <summary>
    /// UC_DrawEdit.xaml 的交互逻辑
    /// </summary>
    public partial class UC_DrawEdit : UserControl, INotifyPropertyChanged
    { 
        /// <summary>
        /// 构造
        /// </summary>
        /// <param name="p_info"></param>
        public UC_DrawEdit(CustomDrawInfo p_info)
        {
            this.p_info = p_info;
            InitializeComponent();
            DataContext = this;

            Loaded += UC_DrawEdit_Loaded;
        }


        #region 变量 + 绑定属性


        private CustomDrawInfo p_info = null;
        private Dictionary<string, List<string>> bindTypePsDict = new Dictionary<string, List<string>>();
        private string[] bindtypeps = new string[4] { "接点", "机台", "区域", "管道" };

        private SolidColorBrush brush_line = new SolidColorBrush(Color.FromRgb(128, 128, 128));
        private SolidColorBrush brush_bg = new SolidColorBrush(Color.FromRgb(33, 40, 48));
        private int bg_ln_thickness = 3;
        private bool showMeshBg = true;
        private bool showMeshRule = true;
        private string imgtmp = AppDomain.CurrentDomain.BaseDirectory + "tmp.png";


        private Point pt_mousedown = new Point();
        private DrawCommand CurrDrawCommand = DrawCommand.无;
        private GridExt MenuItemGrid = null;
        private FrameworkElement curr_draw_shape = null;
        private Point curr_draw_ptdown = new Point();
        private TextBlock curr_draw_text = null;
        private Point curr_draw_ptup = new Point();
        private bool curr_draw_going = false;
        private Dictionary<FrameworkElement, FrameworkElement> shadowDict = new Dictionary<FrameworkElement, FrameworkElement>();
        private List<FrameworkElement> shadow_todrags = new List<FrameworkElement>();
        private bool dragGoing = false;
        private Border bd_slt_area = null;
        private Point pt_select_mousedown = new Point();
        private Point pt_select_mouseup = new Point();
        int end_timeno_1 = 0;


        public ObservableCollection<DrawEleInfo> EleList
        {
            get
            {
                if (CurrDrawInfo.EleList == null) CurrDrawInfo.EleList = new ObservableCollection<DrawEleInfo>();
                return CurrDrawInfo.EleList;
            }
            set
            {
                CurrDrawInfo.EleList = value;
                cc("EleList");
            }
        }
        private DrawEleInfo _EleSelected;
        public DrawEleInfo EleSelected
        {
            get
            {
                return _EleSelected;
            }
            set
            {
                _EleSelected = value;
                cc("EleSelected");
                cc("EleSelectedVisible");

                if (EleList != null) foreach (var v in EleList) v.IsSlt = false;
                if (value != null) value.IsSlt = true;
            }
        }
        public Visibility EleSelectedVisible
        {
            get
            {
                if (EleSelected == null) return Visibility.Collapsed;
                else return Visibility.Visible;
            }
        }
        private CustomDrawInfo _CurrDrawInfo = new CustomDrawInfo();
        public CustomDrawInfo CurrDrawInfo
        {
            get
            {
                return _CurrDrawInfo;
            }
            set
            {
                _CurrDrawInfo = value;
                cc("CurrDrawInfo");
            }
        }

        #endregion


        #region 事件   
        /// <summary>
        /// 页面加载
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void UC_DrawEdit_Loaded(object sender, RoutedEventArgs e)
        {
            APIClient Client = FormMain.Instance.client;

            //列表-接点类型 
            string url = string.Format("api/services/app/HKP_Category/GetList?layout={0}&parentId={1}", "BaseType", 0);
            var result = Client.Get(url);
            ItemsDto<HKP_CategoryDto> res = JsonConvert.DeserializeObject<ItemsDto<HKP_CategoryDto>>(result);
            comboBoxM.DisplayMemberPath = "CateName";
            comboBoxM.SelectedValuePath = "Id";
            comboBoxM.ItemsSource = res?.result?.items;

            //列表-所属系统
            url = string.Format("api/services/app/HKP_System/GetList?maxResultCount={0}", 99999);
            result = Client.Get(url);
            ItemsDto<HKP_SystemDto> dto = JsonConvert.DeserializeObject<ItemsDto<HKP_SystemDto>>(result);
            combSystemId.DisplayMemberPath = "SysNo";
            combSystemId.SelectedValuePath = "Id";
            combSystemId.ItemsSource = dto?.result?.items;


            //cvDrawBg.Width = 500;
            //cvDrawBg.Height = 500;  
            //loadBg(); 
            //LoadBindType();

            cbBindType.ItemsSource = bindtypeps;
            cbBindType.SelectionChanged += CbBindType_SelectionChanged;
            cbBindType.SelectedIndex = 1;

            Task.Run(delegate
            {
                Thread.Sleep(100);
                Dispatcher.Invoke(delegate
                {
                    if (p_info != null)
                    {
                        var infonew = p_info.Clone() as CustomDrawInfo;
                        infonew.EleList = new ObservableCollection<DrawEleInfo>();
                        if (p_info.EleList != null) foreach (var it in p_info.EleList.Select(a => a.Clone() as DrawEleInfo)) infonew.EleList.Add(it);
                        CurrDrawInfo = infonew;
                        if (EleList != null && EleList.Any())
                            foreach (var ele in EleList) doAddDrawEleControl(ele);
                        cc("EleList");
                    }
                    btn_showmapall_click(null, null);
                });
            });
        }
         
        /// <summary>
        /// 切换绑定数据类型
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CbBindType_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (sp_p_jiedian == null) return;
            if (sp_p_sys == null) return;
            if (cbBindType == null) return;
            if (e.AddedItems == null) return;
            if (e.AddedItems.Count == 0) return;

            var newname = e.AddedItems[0].ToString();
            //LoadBindProperties(newname);
            if (newname == "接点")
            {
                sp_p_jiedian.Visibility = Visibility.Visible;
                sp_p_sys.Visibility = Visibility.Collapsed;
            }
            else if (newname == "管道")
            {
                sp_p_jiedian.Visibility = Visibility.Collapsed;
                sp_p_sys.Visibility = Visibility.Visible;
            }
            else
            {
                sp_p_jiedian.Visibility = Visibility.Collapsed;
                sp_p_sys.Visibility = Visibility.Collapsed;
            }
        }

        /// <summary>
        /// 点击按钮-保存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_saveshape_click(object sender, RoutedEventArgs e)
        {
            doSave();
        }
          
        /// <summary>
        /// 点击左侧菜单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void menu_click_shape(object sender, MouseButtonEventArgs e)
        {
            //图形绘制
            var grid = sender as GridExt;
            MenuItemGrid = grid;
            GridExt[] gridsall = new GridExt[] {
                grid_menu_zhixain, grid_menu_quxain, grid_menu_juxing, grid_menu_yuan, grid_menu_wenzi, grid_menu_tuodong, grid_menu_suofang, grid_menu_fuzhi, grid_menu_shanchu,grid_menu_choose };
            foreach (var g in gridsall) g.Tag = "";
            grid.Tag = "Slt";

            CurrDrawCommand = (DrawCommand)Enum.Parse(typeof(DrawCommand), grid.Header);
            if (CurrDrawCommand == DrawCommand.拖动) cvDrawMain.Cursor = Cursors.SizeAll;
            else cvDrawMain.Cursor = Cursors.Cross;



            if (CurrDrawCommand == DrawCommand.删除)
            {
                doDeleteCommand();
            }
            else if (CurrDrawCommand == DrawCommand.复制)
            {
                doCopyCommand();
            }
            else if (CurrDrawCommand == DrawCommand.选择)
            {
                //批量选择
                cvDrawSelect.Visibility = Visibility.Visible;
            }

            //非选择模式
            if (CurrDrawCommand != DrawCommand.选择)
            {
                cvDrawSelect.Visibility = Visibility.Collapsed;
            }
        }

        /// <summary>
        /// 鼠标点击画布
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void canvas_mousedown(object sender, MouseButtonEventArgs e)
        {
            if (CurrDrawCommand == DrawCommand.无) return;
            if (CurrDrawCommand == DrawCommand.拖动) return;
            if (CurrDrawCommand == DrawCommand.复制) return;
            if (CurrDrawCommand == DrawCommand.删除) return;

            if (curr_draw_going)
            {
                if (CurrDrawCommand == DrawCommand.无) return;
                if (CurrDrawCommand != DrawCommand.曲线)
                    curr_draw_going = false;
                else
                {
                    //曲线需要2个标记点,等待2次结束点后终止绘画
                    end_timeno_1++;
                    if (end_timeno_1 == 1) return;
                    else if (end_timeno_1 == 2) curr_draw_going = false;
                }
            }
            else
            {
                draw_start(sender, e);
            }
        }

        /// <summary>
        /// 画图开始
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void draw_start(object sender, MouseButtonEventArgs e)
        {
            if (CurrDrawCommand == DrawCommand.无) return;
            if (CurrDrawCommand == DrawCommand.删除) return;
            if (CurrDrawCommand == DrawCommand.复制) return;
            if (CurrDrawCommand == DrawCommand.拖动) return;
            if (CurrDrawCommand == DrawCommand.缩放) return;
            end_timeno_1 = 0;
            curr_draw_going = true;
            cvDrawMain.Cursor = Cursors.Cross;
            curr_draw_ptdown = e.GetPosition(cvDrawMain);

            //新增绑定对象
            EleSelected = new DrawEleInfo();
            EleSelected.DrawCommand = CurrDrawCommand;
            ////使用上一个绘制图形的线条颜色属性
            //if (EleList.Any(a => a.DrawCommand == CurrDrawCommand))
            //{
            //    var elelast = EleList.Last(a => a.DrawCommand == CurrDrawCommand);
            //    EleSelected = elelast.Clone() as DrawEleInfo;
            //}

            EleSelected.uid = Guid.NewGuid().ToString();
            EleSelected.LocX = curr_draw_ptdown.X;
            EleSelected.LocY = curr_draw_ptdown.Y;
            EleSelected.LocX2 = curr_draw_ptdown.X;
            EleSelected.LocY2 = curr_draw_ptdown.Y;
            EleList.Add(EleSelected);
            ResetRowHeader();
            foreach (var ele in EleList) ele.IsSlt = false;
            EleSelected.IsSlt = true;

            doAddDrawEleControl(EleSelected);
        }

        /// <summary>
        /// 画图中
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void canvas_mousemove(object sender, MouseEventArgs e)
        {
            if (CurrDrawCommand == DrawCommand.无) return;
            if (!curr_draw_going) return;
            if (EleSelected == null) return;

            var curr_draw_new = e.GetPosition(cvDrawMain);

            switch (CurrDrawCommand)
            {
                case DrawCommand.直线:
                case DrawCommand.矩形:
                case DrawCommand.圆形:
                    EleSelected.LocX2 = curr_draw_new.X;
                    EleSelected.LocY2 = curr_draw_new.Y;
                    break;
                case DrawCommand.曲线:
                    if (end_timeno_1 == 0)
                    {
                        EleSelected.LocX2 = curr_draw_new.X;
                        EleSelected.LocY2 = curr_draw_new.Y;
                    }
                    else
                    {
                        EleSelected.Control_1_X = curr_draw_new.X;
                        EleSelected.Control_1_Y = curr_draw_new.Y;
                    }
                    break;
                case DrawCommand.文字:
                    break;
                case DrawCommand.拖动:
                    break;
                case DrawCommand.缩放:
                    break;
                case DrawCommand.复制:
                    break;
                case DrawCommand.删除:
                    break;
                default:
                    break;
            }
        }

        /// <summary>
        /// 开始拖动，仅仅针对于已选中元素
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Shape_MouseDown(object sender, MouseButtonEventArgs e)
        {
            if (e.LeftButton != MouseButtonState.Pressed) return;

            var eletmp = sender as FrameworkElement;
            var eletmpInfo = eletmp.DataContext as DrawEleInfo;
            if (!eletmpInfo.IsSlt) return;

            shadow_todrags.Clear();
            foreach (FrameworkElement fe in cvDrawMain.Children)
            {
                var feinfo = (fe.DataContext as DrawEleInfo);
                if (feinfo == null) continue;
                if (!feinfo.IsSlt) continue;
                shadow_todrags.Add(fe);
            }
            if (CurrDrawCommand == DrawCommand.拖动)
            {
                pt_mousedown = e.GetPosition(cvDrawMain);
                //loc_ele_beforeMove = new Point(Canvas.GetLeft(shadow_todrag), Canvas.GetTop(shadow_todrag));
                dragGoing = true;
                cvDrawMask.Visibility = Visibility.Visible;
            }
            else cvDrawMask.Visibility = Visibility.Collapsed;

        }

        /// <summary>
        /// 拖动中
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cvDrawMask_MouseMove(object sender, MouseEventArgs e)
        {
            if (!dragGoing) return;
            if (CurrDrawCommand == DrawCommand.无) return;
            var curr_draw_new = e.GetPosition(cvDrawMain);

            switch (CurrDrawCommand)
            {
                case DrawCommand.直线:
                case DrawCommand.矩形:
                case DrawCommand.圆形:
                    break;
                case DrawCommand.曲线:
                    break;
                case DrawCommand.文字:
                    break;
                case DrawCommand.拖动:
                    //位移转换
                    var xMove = curr_draw_new.X - pt_mousedown.X;
                    var yMove = curr_draw_new.Y - pt_mousedown.Y;
                    TransformGroup rt = new TransformGroup();
                    rt.Children.Add(new TranslateTransform(xMove, yMove));

                    foreach (var shadow_todrag in shadow_todrags)
                    {
                        if (!shadowDict.ContainsKey(shadow_todrag)) continue;

                        shadow_todrag.RenderTransform = rt;
                        shadowDict[shadow_todrag].RenderTransform = rt;
                    }
                    break;
                case DrawCommand.缩放:
                    break;
                case DrawCommand.复制:
                    break;
                case DrawCommand.删除:
                    break;
                default:
                    break;
            }

        }

        /// <summary>
        /// 停止拖动
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cvDrawMask_MouseDown(object sender, MouseButtonEventArgs e)
        {
            if (!dragGoing) return;
            if (CurrDrawCommand == DrawCommand.无) return;
            var curr_draw_new = e.GetPosition(cvDrawMain);

            switch (CurrDrawCommand)
            {
                case DrawCommand.直线:
                case DrawCommand.矩形:
                case DrawCommand.圆形:
                    break;
                case DrawCommand.曲线:
                    break;
                case DrawCommand.文字:
                    break;
                case DrawCommand.拖动:
                    var xMove = curr_draw_new.X - pt_mousedown.X;
                    var yMove = curr_draw_new.Y - pt_mousedown.Y;
                    foreach (var shadow_todrag in shadow_todrags)
                    {
                        if (!shadowDict.ContainsKey(shadow_todrag)) continue;
                        shadow_todrag.RenderTransform = null;
                        shadowDict[shadow_todrag].RenderTransform = null;

                        var eleinfo = shadow_todrag.DataContext as DrawEleInfo;
                        eleinfo.LocX += xMove;
                        eleinfo.LocY += yMove;

                        if (eleinfo.DrawCommand == DrawCommand.曲线
                            || eleinfo.DrawCommand == DrawCommand.直线
                            )
                        {
                            eleinfo.LocX2 += xMove;
                            eleinfo.LocY2 += yMove;
                        }
                        if (eleinfo.DrawCommand == DrawCommand.曲线)
                        {
                            eleinfo.Control_1_X += xMove;
                            eleinfo.Control_1_Y += yMove;
                        }
                    }

                    dragGoing = false;
                    cvDrawMask.Visibility = Visibility.Collapsed;
                    break;
                case DrawCommand.缩放:
                    break;
                case DrawCommand.复制:
                    break;
                case DrawCommand.删除:
                    break;
                default:
                    break;
            }
        }

        /// <summary>
        /// 鼠标悬浮元素
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void New_line_MouseMove(object sender, MouseEventArgs e)
        {
            var ln = sender as FrameworkElement;
            (ln.DataContext as DrawEleInfo).IsMouseOver = true;

            //if (ln.Tag != null && ln.Tag.ToString() == "ismouseover") return;

            //ln.Tag = "ismouseover";
            //if (ln is Shape) (ln as Shape).Stroke = bs_red_mouseover;
            //else if (ln is Border) (ln as Border).BorderBrush = bs_red_mouseover;
        }

        /// <summary>
        /// 鼠标悬浮元素结束
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void New_line_MouseLeave(object sender, MouseEventArgs e)
        {
            var ln = sender as FrameworkElement;
            (ln.DataContext as DrawEleInfo).IsMouseOver = false;
            //只要选中，就显示为悬浮效果
            //if ((ln.DataContext as DrawEleInfo).IsSlt) return; 
            //if (ln is Shape) (ln as Shape).Stroke = Brushes.Transparent;
            //else if (ln is Border) (ln as Border).BorderBrush = Brushes.Transparent;
        }

        /// <summary>
        /// 清空画布
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_cleardraw_click(object sender, RoutedEventArgs e)
        {
            cvDrawMain.Children.Clear();
            if (EleList.Any()) EleList.Clear();
            EleSelected = null;
        }

        /// <summary>
        /// 列表中删除指定元素
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_del_item(object sender, RoutedEventArgs e)
        {
            var eleinfo = (sender as Button).DataContext as DrawEleInfo;
            delItem(eleinfo);
        }

        /// <summary>
        /// 画布批量选择-鼠标按下
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cvDrawSelect_MouseDown(object sender, MouseButtonEventArgs e)
        {
            if (e.LeftButton != MouseButtonState.Pressed) return;

            pt_select_mousedown = e.GetPosition(cvDrawSelect);

            //全选区域，选择区域内元素，支持批量选择
            bd_slt_area = new Border() { Width = 10, Height = 10 };
            bd_slt_area.BorderBrush = Brushes.White;
            bd_slt_area.Background = Brushes.White;
            bd_slt_area.Opacity = 0.3;
            Canvas.SetLeft(bd_slt_area, pt_select_mousedown.X);
            Canvas.SetTop(bd_slt_area, pt_select_mousedown.Y);
            cvDrawMain.Children.Add(bd_slt_area);

        }

        /// <summary>
        /// 画布批量选择-鼠标按下移动
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cvDrawSelect_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.LeftButton != MouseButtonState.Pressed) return;
            if (bd_slt_area == null) return;

            pt_select_mouseup = e.GetPosition(cvDrawSelect);

            var width = Math.Max(10, pt_select_mouseup.X - pt_select_mousedown.X);
            var height = Math.Max(10, pt_select_mouseup.Y - pt_select_mousedown.Y);
            bd_slt_area.Width = width;
            bd_slt_area.Height = height;
        }

        /// <summary>
        /// 画布批量选择-鼠标抬起
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cvDrawSelect_MouseUp(object sender, MouseButtonEventArgs e)
        {
            if (bd_slt_area == null) return;

            //移除全选标记
            cvDrawMain.Children.Remove(bd_slt_area);

            //当前全选区域
            var rt_slt = new Rect(Canvas.GetLeft(bd_slt_area),
                Canvas.GetTop(bd_slt_area),
                bd_slt_area.Width,
                bd_slt_area.Height
                );

            //选择该区域的元素
            List<FrameworkElement> fe_slt_lst = new List<FrameworkElement>();
            foreach (var fe in cvDrawMain.Children.Cast<FrameworkElement>().Where(a => a != bd_slt_area))
            {
                var eleinfo = (fe as FrameworkElement).DataContext as DrawEleInfo;
                if (eleinfo == null) continue;

                var rt = new Rect(eleinfo.LocX, eleinfo.LocY, eleinfo.SizeWidth, eleinfo.SizeHeight);
                if (rt.IntersectsWith(rt_slt)) fe_slt_lst.Add(fe);//区域内的加入
                else eleinfo.IsSlt = false;  //区域外的不选中
            }

            //仅仅显示第一个的相关属性信息
            if (fe_slt_lst.Any()) EleSelected = (fe_slt_lst.First().DataContext as DrawEleInfo);

            //设置为选中
            foreach (var ele in EleList) ele.IsSlt = false;
            foreach (var fe in fe_slt_lst) (fe.DataContext as DrawEleInfo).IsSlt = true;

            bd_slt_area = null;
        }

        /// <summary>
        /// 设置边框线
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Border_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            var scb = Brushes.Black;
            if (!ColorSelector(out scb)) return;


            if (EleSelected == null) return;
            EleSelected.Stroke = scb;
        }

        /// <summary>
        /// 设置填充色
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Border_MouseLeftButtonDown_fill(object sender, MouseButtonEventArgs e)
        {
            var scb = Brushes.Black;
            if (!ColorSelector(out scb)) return;

            if (EleSelected == null) return;
            EleSelected.Fill = scb;
        }

        /// <summary>
        /// 表格行头序号
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DataGrid_LoadingRow(object sender, DataGridRowEventArgs e)
        {
            e.Row.Header = e.Row.GetIndex() + 1;
        }

        /// <summary>
        /// 导出图形
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_exportshape_click(object sender, RoutedEventArgs e)
        {
            if (EleList == null || EleList.Count == 0)
            {
                MessageBox.Show("没有需要导出的内容！");
                return;
            }
            try
            {
                var shapeExport = CurrDrawInfo;
                var jstr = Newtonsoft.Json.JsonConvert.SerializeObject(shapeExport);
                byte[] b = System.Text.Encoding.Default.GetBytes(jstr);
                var bstr = Convert.ToBase64String(b);
                var sfd = new System.Windows.Forms.SaveFileDialog();
                sfd.FileName = "导出图形_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".HDCDRAW";
                if (sfd.ShowDialog() != System.Windows.Forms.DialogResult.OK) return;

                System.IO.File.WriteAllText(sfd.FileName, bstr);
                MessageBox.Show("导出成功！");
            }
            catch (Exception)
            {
                MessageBox.Show("导出图形发生了异常，请稍后重试！");
            }
        }

        /// <summary>
        /// 导入图形
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_importshape_click(object sender, RoutedEventArgs e)
        {
            try
            {
                var ofd = new System.Windows.Forms.OpenFileDialog();
                ofd.Filter = "*.HDCDRAW|*.HDCDRAW";
                ofd.Multiselect = false;
                if (ofd.ShowDialog() != System.Windows.Forms.DialogResult.OK) return;

                //清除现有的
                EleList.Clear();
                cvDrawMain.Children.Clear();
                EleSelected = null;



                var bstr = System.IO.File.ReadAllText(ofd.FileName);
                byte[] c = Convert.FromBase64String(bstr);
                var jstr = System.Text.Encoding.Default.GetString(c);
                var shapeExport = Newtonsoft.Json.JsonConvert.DeserializeObject<CustomDrawInfo>(jstr);
                CurrDrawInfo = (CustomDrawInfo)shapeExport;
                EleList = (ObservableCollection<DrawEleInfo>)shapeExport.EleList;

                foreach (var ele in EleList) doAddDrawEleControl(ele);

                MessageBox.Show("导入成功！");

            }
            catch (Exception)
            {
                MessageBox.Show("导入图形发生了异常，请导入有效的图形文件！");
            }
        }

        /// <summary>
        /// 显示背景
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CheckBox_Checked(object sender, RoutedEventArgs e)
        {

            showMeshBg = true;
            loadBg();
        }

        /// <summary>
        /// 隐藏背景
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param> 
        private void CheckBox_Unchecked(object sender, RoutedEventArgs e)
        {
            showMeshBg = false;
            loadBg();
        }

        /// <summary>
        /// 显示刻度
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CheckBox_Checked_1(object sender, RoutedEventArgs e)
        {
            showMeshRule = true;
            loadBg();
        }

        /// <summary>
        /// 隐藏刻度
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CheckBox_Unchecked_1(object sender, RoutedEventArgs e)
        {
            showMeshRule = false;
            loadBg();
        }

        #endregion

        #region 方法 

        /// <summary>
        /// 加载网格背景
        /// </summary>
        private void loadBg()
        {
            //不使用背景
            //showMeshBg = false;
            //showMeshRule = false; 

            if (cvDrawBg == null) return;

            cvDrawBg.Children.Clear();


            //可调整变量
            //总列数
            int colCount = 20 / 1;
            //总行数
            int rowCount = 13 / 1;
            //列宽
            var colWidthItem = 200d;
            //行高
            var rowHeightItem = 130d;
            //背景线条颜色
            brush_line = new SolidColorBrush(Color.FromRgb(128, 128, 128));
            //背景色
            brush_bg = new SolidColorBrush(Color.FromRgb(33, 40, 48));
            //背景线条宽度
            bg_ln_thickness = 3;
            //4边突出长度
            var outter_extlen = 50;



            var colCount2 = colCount;
            var rowCount2 = rowCount;
            colCount2 += 4;
            rowCount2 += 4;


            var widthall = colWidthItem * colCount2;
            var heightall = rowHeightItem * rowCount2;

            cvDrawBg.Width = widthall;
            cvDrawBg.Height = heightall;


            //缩放至正好最大看见
            var tflist = cvDrawBg.RenderTransform as TransformGroup;
            var sf1 = tflist.Children[1] as TranslateTransform;


            if (showMeshBg)
            {
                #region 背景线条
                //背景线条-横线
                var x = colWidthItem * 1;
                var rowMaxCount = rowCount2 - 1 + 1;
                for (int r = 1; r < rowMaxCount; r++)
                {
                    var ln = new Line();
                    ln.StrokeThickness = bg_ln_thickness;
                    ln.Stroke = brush_line;
                    if (r == 1 || r == rowMaxCount - 1)
                    {
                        ln.X1 = colWidthItem * 2;
                        ln.X2 = widthall - colWidthItem * 2;
                    }
                    else
                    {
                        ln.X1 = x - outter_extlen;
                        ln.X2 = widthall - colWidthItem * 1 + outter_extlen;
                    }
                    ln.Y1 = r * rowHeightItem;
                    ln.Y2 = r * rowHeightItem;

                    cvDrawBg.Children.Add(ln);
                }
                var y = rowHeightItem * 1;
                //背景线条-竖线
                var colMaxCount = colCount2 - 1 + 1;
                for (int c = 1; c < colMaxCount; c++)
                {
                    var ln = new Line();
                    ln.StrokeThickness = bg_ln_thickness;
                    ln.Stroke = brush_line;
                    ln.X1 = c * colWidthItem;
                    ln.X2 = c * colWidthItem;
                    if (c == 1 || c == colMaxCount - 1)
                    {
                        ln.Y1 = rowHeightItem * 2;
                        ln.Y2 = heightall - rowHeightItem * 2;
                    }
                    else
                    {
                        ln.Y1 = y - outter_extlen;
                        ln.Y2 = heightall - rowHeightItem * 1 + outter_extlen;
                    }

                    cvDrawBg.Children.Add(ln);
                }

                //背景方框
                for (int r = 2; r < rowCount2 - 2 + 1; r++)
                {
                    for (int c = 2; c < colCount2 - 2 + 1; c++)
                    {
                        //外框
                        var x1 = c * colWidthItem;
                        var y1 = r * rowHeightItem;
                        var len_half = colWidthItem * 0.3;
                        x1 -= len_half * 0.5;
                        y1 -= len_half * 0.5;
                        var lenrt = len_half;

                        var ln = new Rectangle();
                        ln.Fill = brush_bg;
                        ln.Width = lenrt;
                        ln.Height = lenrt;
                        Canvas.SetLeft(ln, x1);
                        Canvas.SetTop(ln, y1);
                        cvDrawBg.Children.Add(ln);

                        //内框
                        x1 = c * colWidthItem;
                        y1 = r * rowHeightItem;
                        len_half = colWidthItem * 0.15;
                        x1 -= len_half * 0.5;
                        y1 -= len_half * 0.5;
                        lenrt = len_half;

                        ln = new Rectangle();
                        ln.Fill = brush_line;
                        ln.Width = lenrt;
                        ln.Height = lenrt;
                        Canvas.SetLeft(ln, x1);
                        Canvas.SetTop(ln, y1);
                        cvDrawBg.Children.Add(ln);
                    }
                }
                #endregion
            }

            if (showMeshRule)
            {
                #region 刻度  序号
                //序号-上 
                for (int c = 2; c < colCount2 - 2 + 1; c++)
                {
                    //外圆圈 
                    var len_half = colWidthItem * 0.3;
                    var x1 = c * colWidthItem;
                    var y1 = 1 * rowHeightItem - outter_extlen - len_half * 0.5;
                    x1 -= len_half * 0.5;
                    y1 -= len_half * 0.5;
                    var lenrt = len_half;

                    var ln = new Ellipse();
                    ln.StrokeThickness = bg_ln_thickness;
                    ln.Stroke = brush_line;
                    ln.Width = lenrt;
                    ln.Height = lenrt;
                    Canvas.SetLeft(ln, x1);
                    Canvas.SetTop(ln, y1);
                    cvDrawBg.Children.Add(ln);

                    //内部文字
                    var txt = new Label();
                    txt.Width = lenrt;
                    txt.Height = lenrt;
                    txt.Content = (c - 1).ToString();
                    txt.FontSize = 24;
                    txt.Foreground = Brushes.White;
                    txt.HorizontalContentAlignment = HorizontalAlignment.Center;
                    txt.VerticalContentAlignment = VerticalAlignment.Center;
                    Canvas.SetLeft(txt, x1);
                    Canvas.SetTop(txt, y1);
                    cvDrawBg.Children.Add(txt);

                }

                //序号-下
                for (int c = 2; c < colCount2 - 2 + 1; c++)
                {
                    //外圆圈 
                    var len_half = colWidthItem * 0.3;
                    var x1 = c * colWidthItem;
                    var y1 = heightall - 1 * rowHeightItem + outter_extlen + len_half * 0.5;
                    x1 -= len_half * 0.5;
                    y1 -= len_half * 0.5;
                    var lenrt = len_half;

                    var ln = new Ellipse();
                    ln.StrokeThickness = bg_ln_thickness;
                    ln.Stroke = brush_line;
                    ln.Width = lenrt;
                    ln.Height = lenrt;
                    Canvas.SetLeft(ln, x1);
                    Canvas.SetTop(ln, y1);
                    cvDrawBg.Children.Add(ln);

                    //内部文字
                    var txt = new Label();
                    txt.Width = lenrt;
                    txt.Height = lenrt;
                    txt.Content = (c - 1).ToString();
                    txt.FontSize = 24;
                    txt.Foreground = Brushes.White;
                    txt.HorizontalContentAlignment = HorizontalAlignment.Center;
                    txt.VerticalContentAlignment = VerticalAlignment.Center;
                    Canvas.SetLeft(txt, x1);
                    Canvas.SetTop(txt, y1);
                    cvDrawBg.Children.Add(txt);

                }
                //序号-左侧  
                var maxno = rowCount2 - 2 + 1;
                for (int r = 2; r < maxno; r++)
                {
                    //外圆圈 
                    var len_half = rowHeightItem * 0.3;
                    var x1 = 1 * colWidthItem - outter_extlen - len_half * 0.5;
                    var y1 = r * rowHeightItem;
                    x1 -= len_half * 0.5;
                    y1 -= len_half * 0.5;
                    var lenrt = len_half;

                    var ln = new Ellipse();
                    ln.StrokeThickness = bg_ln_thickness;
                    ln.Stroke = brush_line;
                    ln.Width = lenrt;
                    ln.Height = lenrt;
                    Canvas.SetLeft(ln, x1);
                    Canvas.SetTop(ln, y1);
                    cvDrawBg.Children.Add(ln);

                    //内部文字
                    var txt = new Label();
                    txt.Width = lenrt;
                    txt.Height = lenrt;
                    txt.Content = ((char)(((int)'N') - (r - 2))).ToString();
                    txt.FontSize = 24;
                    txt.Foreground = Brushes.White;
                    txt.HorizontalContentAlignment = HorizontalAlignment.Center;
                    txt.VerticalContentAlignment = VerticalAlignment.Center;
                    Canvas.SetLeft(txt, x1);
                    Canvas.SetTop(txt, y1);
                    cvDrawBg.Children.Add(txt);

                }
                //序号-右侧  
                maxno = rowCount2 - 2 + 1;
                for (int r = 2; r < maxno; r++)
                {
                    //外圆圈 
                    var len_half = rowHeightItem * 0.3;
                    var x1 = widthall - 1 * colWidthItem + outter_extlen + len_half * 0.5;
                    var y1 = r * rowHeightItem;
                    x1 -= len_half * 0.5;
                    y1 -= len_half * 0.5;
                    var lenrt = len_half;

                    var ln = new Ellipse();
                    ln.StrokeThickness = bg_ln_thickness;
                    ln.Stroke = brush_line;
                    ln.Width = lenrt;
                    ln.Height = lenrt;
                    Canvas.SetLeft(ln, x1);
                    Canvas.SetTop(ln, y1);
                    cvDrawBg.Children.Add(ln);

                    //内部文字
                    var txt = new Label();
                    txt.Width = lenrt;
                    txt.Height = lenrt;
                    txt.Content = ((char)(((int)'N') - (r - 2))).ToString();
                    txt.FontSize = 24;
                    txt.Foreground = Brushes.White;
                    txt.HorizontalContentAlignment = HorizontalAlignment.Center;
                    txt.VerticalContentAlignment = VerticalAlignment.Center;
                    Canvas.SetLeft(txt, x1);
                    Canvas.SetTop(txt, y1);
                    cvDrawBg.Children.Add(txt);

                }

                //刻度单位说明-上 
                for (int c = 2; c < colCount2 - 2; c++)
                {
                    // 文字
                    var txt = new Label();
                    txt.Width = colWidthItem;
                    txt.Content = ((int)colWidthItem).ToString();
                    txt.FontSize = 24;
                    txt.Foreground = Brushes.White;
                    txt.HorizontalContentAlignment = HorizontalAlignment.Center;
                    txt.VerticalContentAlignment = VerticalAlignment.Bottom;
                    Canvas.SetLeft(txt, colWidthItem * c);
                    Canvas.SetTop(txt, rowHeightItem * 1 - 50);
                    cvDrawBg.Children.Add(txt);

                } //刻度单位说明-下 
                for (int c = 2; c < colCount2 - 2; c++)
                {
                    // 文字
                    var txt = new Label();
                    txt.Width = colWidthItem;
                    txt.Content = ((int)colWidthItem).ToString();
                    txt.FontSize = 24;
                    txt.Foreground = Brushes.White;
                    txt.HorizontalContentAlignment = HorizontalAlignment.Center;
                    txt.VerticalContentAlignment = VerticalAlignment.Top;
                    Canvas.SetLeft(txt, colWidthItem * c);
                    Canvas.SetTop(txt, heightall - rowHeightItem * 1 + 10);
                    cvDrawBg.Children.Add(txt);

                }

                //刻度单位说明-左侧 
                var trans1 = FindResource("tfg1") as TransformGroup;
                for (int r = 2; r < rowCount2 - 2; r++)
                {
                    // 文字
                    var txt = new Label();
                    txt.RenderTransformOrigin = new Point(0.5, 0.5);
                    txt.RenderTransform = trans1;
                    txt.Height = rowHeightItem;
                    txt.Content = ((int)rowHeightItem).ToString();
                    txt.FontSize = 24;
                    txt.Foreground = Brushes.White;
                    txt.HorizontalContentAlignment = HorizontalAlignment.Right;
                    txt.VerticalContentAlignment = VerticalAlignment.Center;
                    Canvas.SetLeft(txt, colWidthItem * 1 - 60);
                    Canvas.SetTop(txt, rowHeightItem * r);
                    cvDrawBg.Children.Add(txt);

                }
                //刻度单位说明-右侧 
                var trans2 = FindResource("tfg2") as TransformGroup;
                for (int r = 2; r < rowCount2 - 2; r++)
                {
                    // 文字
                    var txt = new Label();
                    txt.RenderTransformOrigin = new Point(0.5, 0.5);
                    txt.RenderTransform = trans2;
                    txt.Height = rowHeightItem;
                    txt.Content = ((int)rowHeightItem).ToString();
                    txt.FontSize = 24;
                    txt.Foreground = Brushes.White;
                    txt.HorizontalContentAlignment = HorizontalAlignment.Left;
                    txt.VerticalContentAlignment = VerticalAlignment.Center;
                    Canvas.SetLeft(txt, widthall - colWidthItem * 1 + 00);
                    Canvas.SetTop(txt, rowHeightItem * r);
                    cvDrawBg.Children.Add(txt);

                }
                #endregion

            }
        }
         
        /// <summary>
        /// 根据上下文添加一个控件
        /// </summary>
        /// <param name="EleSelected"></param>
        private void doAddDrawEleControl(DrawEleInfo EleSelected)
        {
            Dispatcher.Invoke(delegate
            {
                switch (EleSelected.DrawCommand)
                {
                    case DrawCommand.直线:
                        var new_line = new Line();
                        new_line.DataContext = EleSelected;
                        new_line.Width = cvDrawMain.ActualWidth;
                        new_line.Height = cvDrawMain.ActualHeight;
                        new_line.SetBinding(Line.StrokeProperty, new Binding() { Path = new PropertyPath("Stroke") });
                        new_line.SetBinding(Line.StrokeThicknessProperty, new Binding() { Path = new PropertyPath("StrokeThickness") });
                        new_line.SetBinding(Line.FillProperty, new Binding() { Path = new PropertyPath("Fill") });
                        new_line.SetBinding(Line.X1Property, new Binding() { Path = new PropertyPath("LocX") });
                        new_line.SetBinding(Line.Y1Property, new Binding() { Path = new PropertyPath("LocY") });
                        new_line.SetBinding(Line.X2Property, new Binding() { Path = new PropertyPath("LocX2") });
                        new_line.SetBinding(Line.Y2Property, new Binding() { Path = new PropertyPath("LocY2") });
                        cvDrawMain.Children.Add(new_line);
                        curr_draw_shape = new_line;

                        new_line = new Line();
                        new_line.DataContext = EleSelected;
                        new_line.Width = cvDrawMain.ActualWidth;
                        new_line.Height = cvDrawMain.ActualHeight;
                        new_line.Fill = Brushes.Transparent;
                        new_line.SetBinding(Line.StrokeProperty, new Binding() { Path = new PropertyPath("StrokeShadow") });
                        new_line.SetBinding(Line.StrokeThicknessProperty, new Binding() { Path = new PropertyPath("StrokeShadowThickness") });
                        new_line.SetBinding(Line.X1Property, new Binding() { Path = new PropertyPath("LocX") });
                        new_line.SetBinding(Line.Y1Property, new Binding() { Path = new PropertyPath("LocY") });
                        new_line.SetBinding(Line.X2Property, new Binding() { Path = new PropertyPath("LocX2") });
                        new_line.SetBinding(Line.Y2Property, new Binding() { Path = new PropertyPath("LocY2") });
                        new_line.MouseMove += New_line_MouseMove;
                        new_line.MouseLeave += New_line_MouseLeave;
                        new_line.MouseDown += Shape_MouseDown;
                        shadowDict.Add(new_line, curr_draw_shape);
                        cvDrawMain.Children.Add(new_line);

                        break;
                    case DrawCommand.曲线:

                        //                      <!--鼠标首次点下时，固定path的canvas位置；鼠标二次点下时，固定结束点（StartPoint) ; 鼠标三次点下时，固定控制点，Point1-->
                        //      <Path  Stroke="#1ba1ea" StrokeThickness="5" 
                        //RenderTransformOrigin="0.5 0.5"   Fill="Red" >
                        //          <Path.Data>
                        //              <PathGeometry>
                        //                  <PathGeometry.Figures>
                        //                      <PathFigure StartPoint="150,10 "   >
                        //                          <!--M 150,10 S 250,100 80,280-->
                        //                          <!--Point1:第一个控制点   Point2：第二个控制点-->
                        //                          <BezierSegment  IsSmoothJoin="True" Point1="80,280" />
                        //                      </PathFigure>
                        //                  </PathGeometry.Figures>
                        //              </PathGeometry>
                        //          </Path.Data>
                        //      </Path>

                        //或者 Data = "M30,0  S80,280  150,10"    起始点，控制点，结束点
                        var new_curve = new System.Windows.Shapes.Path();
                        new_curve.DataContext = EleSelected;
                        new_curve.Width = cvDrawMain.ActualWidth;
                        new_curve.Height = cvDrawMain.ActualHeight;
                        new_curve.SetBinding(System.Windows.Shapes.Path.StrokeProperty, new Binding() { Path = new PropertyPath("Stroke") });
                        new_curve.SetBinding(System.Windows.Shapes.Path.StrokeThicknessProperty, new Binding() { Path = new PropertyPath("StrokeThickness") });
                        new_curve.SetBinding(System.Windows.Shapes.Path.FillProperty, new Binding() { Path = new PropertyPath("FillWidthOpacity") });
                        new_curve.SetBinding(System.Windows.Shapes.Path.DataProperty, new Binding() { Path = new PropertyPath("CurveDataStr") });
                        cvDrawMain.Children.Add(new_curve);
                        curr_draw_shape = new_curve;

                        new_curve = new System.Windows.Shapes.Path();
                        new_curve.DataContext = EleSelected;
                        new_curve.Width = cvDrawMain.ActualWidth;
                        new_curve.Height = cvDrawMain.ActualHeight;
                        new_curve.Fill = Brushes.Transparent;
                        new_curve.SetBinding(System.Windows.Shapes.Path.StrokeProperty, new Binding() { Path = new PropertyPath("StrokeShadow") });
                        new_curve.SetBinding(System.Windows.Shapes.Path.StrokeThicknessProperty, new Binding() { Path = new PropertyPath("StrokeShadowThickness") });
                        new_curve.SetBinding(System.Windows.Shapes.Path.DataProperty, new Binding() { Path = new PropertyPath("CurveDataStr") });
                        new_curve.MouseMove += New_line_MouseMove;
                        new_curve.MouseLeave += New_line_MouseLeave;
                        new_curve.MouseDown += Shape_MouseDown;
                        shadowDict.Add(new_curve, curr_draw_shape);
                        cvDrawMain.Children.Add(new_curve);

                        break;
                    case DrawCommand.矩形:
                        var new_rect = new Border();
                        new_rect.DataContext = EleSelected;
                        new_rect.SetBinding(Border.BorderBrushProperty, new Binding() { Path = new PropertyPath("Stroke") });
                        new_rect.SetBinding(Border.BorderThicknessProperty, new Binding() { Path = new PropertyPath("StrokeThickness") });
                        new_rect.SetBinding(Border.BackgroundProperty, new Binding() { Path = new PropertyPath("FillWidthOpacity") });
                        new_rect.SetBinding(Canvas.LeftProperty, new Binding() { Path = new PropertyPath("LocX") });
                        new_rect.SetBinding(Canvas.TopProperty, new Binding() { Path = new PropertyPath("LocY") });
                        new_rect.SetBinding(Border.WidthProperty, new Binding() { Path = new PropertyPath("SizeWidth") });
                        new_rect.SetBinding(Border.HeightProperty, new Binding() { Path = new PropertyPath("SizeHeight") });
                        new_rect.SetBinding(Border.CornerRadiusProperty, new Binding() { Path = new PropertyPath("BorderRadius") });
                        cvDrawMain.Children.Add(new_rect);
                        curr_draw_shape = new_rect;



                        new_rect = new Border();
                        new_rect.DataContext = EleSelected;
                        new_rect.Width = cvDrawMain.ActualWidth;
                        new_rect.Height = cvDrawMain.ActualHeight;
                        new_rect.Background = Brushes.Transparent;
                        new_rect.SetBinding(Border.BorderBrushProperty, new Binding() { Path = new PropertyPath("StrokeShadow") });
                        new_rect.SetBinding(Border.BorderThicknessProperty, new Binding() { Path = new PropertyPath("StrokeShadowThickness") });
                        new_rect.SetBinding(Canvas.LeftProperty, new Binding() { Path = new PropertyPath("LocX") });
                        new_rect.SetBinding(Canvas.TopProperty, new Binding() { Path = new PropertyPath("LocY") });
                        new_rect.SetBinding(Border.WidthProperty, new Binding() { Path = new PropertyPath("SizeWidth") });
                        new_rect.SetBinding(Border.HeightProperty, new Binding() { Path = new PropertyPath("SizeHeight") });
                        new_rect.SetBinding(Border.CornerRadiusProperty, new Binding() { Path = new PropertyPath("BorderRadius") });
                        new_rect.MouseMove += New_line_MouseMove;
                        new_rect.MouseLeave += New_line_MouseLeave;
                        new_rect.MouseDown += Shape_MouseDown;
                        shadowDict.Add(new_rect, curr_draw_shape);
                        cvDrawMain.Children.Add(new_rect);

                        break;
                    case DrawCommand.圆形:
                        var new_ell = new Ellipse();
                        new_ell.DataContext = EleSelected;
                        new_ell.SetBinding(Ellipse.StrokeProperty, new Binding() { Path = new PropertyPath("Stroke") });
                        new_ell.SetBinding(Ellipse.StrokeThicknessProperty, new Binding() { Path = new PropertyPath("StrokeThickness") });
                        new_ell.SetBinding(Ellipse.FillProperty, new Binding() { Path = new PropertyPath("FillWidthOpacity") });
                        new_ell.SetBinding(Canvas.LeftProperty, new Binding() { Path = new PropertyPath("LocX") });
                        new_ell.SetBinding(Canvas.TopProperty, new Binding() { Path = new PropertyPath("LocY") });
                        new_ell.SetBinding(Ellipse.WidthProperty, new Binding() { Path = new PropertyPath("SizeWidth") });
                        new_ell.SetBinding(Ellipse.HeightProperty, new Binding() { Path = new PropertyPath("SizeHeight") });
                        cvDrawMain.Children.Add(new_ell);
                        curr_draw_shape = new_ell;


                        new_ell = new Ellipse();
                        new_ell.DataContext = EleSelected;
                        new_ell.Width = cvDrawMain.ActualWidth;
                        new_ell.Height = cvDrawMain.ActualHeight;
                        new_ell.Fill = Brushes.Transparent;
                        new_ell.SetBinding(Line.StrokeProperty, new Binding() { Path = new PropertyPath("StrokeShadow") });
                        new_ell.SetBinding(Rectangle.StrokeThicknessProperty, new Binding() { Path = new PropertyPath("StrokeShadowThickness") });
                        new_ell.SetBinding(Canvas.LeftProperty, new Binding() { Path = new PropertyPath("LocX") });
                        new_ell.SetBinding(Canvas.TopProperty, new Binding() { Path = new PropertyPath("LocY") });
                        new_ell.SetBinding(Rectangle.WidthProperty, new Binding() { Path = new PropertyPath("SizeWidth") });
                        new_ell.SetBinding(Rectangle.HeightProperty, new Binding() { Path = new PropertyPath("SizeHeight") });
                        new_ell.MouseMove += New_line_MouseMove;
                        new_ell.MouseLeave += New_line_MouseLeave;
                        new_ell.MouseDown += Shape_MouseDown;
                        shadowDict.Add(new_ell, curr_draw_shape);
                        cvDrawMain.Children.Add(new_ell);


                        break;
                    case DrawCommand.文字:
                        var new_text = new TextBlock() { };
                        new_text.DataContext = EleSelected;
                        new_text.SetBinding(TextBlock.ForegroundProperty, new Binding() { Path = new PropertyPath("Stroke") });
                        new_text.SetBinding(TextBlock.FontSizeProperty, new Binding() { Path = new PropertyPath("FontSize") });
                        new_text.SetBinding(TextBlock.BackgroundProperty, new Binding() { Path = new PropertyPath("FillWidthOpacity") });
                        new_text.SetBinding(TextBlock.TextProperty, new Binding() { Path = new PropertyPath("TextStr") });
                        new_text.SetBinding(Canvas.LeftProperty, new Binding() { Path = new PropertyPath("LocX") });
                        new_text.SetBinding(Canvas.TopProperty, new Binding() { Path = new PropertyPath("LocY") });
                        new_text.MouseMove += New_line_MouseMove;
                        new_text.MouseLeave += New_line_MouseLeave;
                        new_text.MouseDown += Shape_MouseDown;
                        shadowDict.Add(new_text, new_text);
                        EleSelected.TextStr = "新增文本";
                        cvDrawMain.Children.Add(new_text);
                        curr_draw_text = new_text;

                        //结束画图
                        curr_draw_going = false;

                        break;
                    case DrawCommand.拖动:
                        break;
                    case DrawCommand.缩放:
                        break;
                    case DrawCommand.复制:
                        break;
                    case DrawCommand.删除:
                        break;
                    default:
                        break;
                }
            });
        }
         
        private void doSave()
        {
            var sname = CurrDrawInfo.ShapeName;
            if (string.IsNullOrWhiteSpace(sname))
            {
                MessageBox.Show("请输入有效的图形名称！");
                return;
            }
            if (CurrDrawInfo.BindDataType == "接点")
                CurrDrawInfo.BindDataProperty = comboBoxM.Text;
            else if (CurrDrawInfo.BindDataType == "管道")
                CurrDrawInfo.BindDataProperty = combSystemId.Text;
            else CurrDrawInfo.BindDataProperty = "";


            //生成预览图像
            var imgpre = GenPreviewImg();
            if (imgpre != null)
            {
                imgpre = ResizeMap(imgpre, 200);
                imgpre.Save(imgtmp);
                CurrDrawInfo.PreviewImg = File.ReadAllBytes(imgtmp);
                imgpre.Dispose();
            }

            //执行数据保存  
            var saverst = false;
            if (string.IsNullOrWhiteSpace(CurrDrawInfo.uid))
            {
                CurrDrawInfo.uid = Guid.NewGuid().ToString();
                saverst = LocalDataHelper.AddShape(CurrDrawInfo);
            }
            else
            {
                saverst = LocalDataHelper.UpdateShape(CurrDrawInfo);
            }

            if (saverst)
            {
                MessageBox.Show("操作成功！");
            }
            else
            {
                MessageBox.Show("操作失败！");
            }
        }

        private System.Drawing.Bitmap GenPreviewImg()
        {
            var ImgScaleX_old = ImgScaleX;
            var ImgScaleY_old = ImgScaleY;
            var ImgMoveX_old = ImgMoveX;
            var ImgMoveY_old = ImgMoveY;

            ImgScaleX = 1;
            ImgScaleY = 1;
            ImgMoveX = 0;
            ImgMoveY = 0;


            System.Drawing.Bitmap rstmap = null;

            try
            {

                if (EleList == null || EleList.Count == 0) return rstmap;

                //生成预览图形 
                RenderTargetBitmap bmp = new RenderTargetBitmap((int)cvDrawMain.ActualWidth, (int)cvDrawMain.ActualHeight, 96, 96, PixelFormats.Pbgra32);
                bmp.Render(cvDrawMain);
                string file = imgtmp;
                BitmapEncoder encoder = new PngBitmapEncoder();
                encoder.Frames.Add(BitmapFrame.Create(bmp));
                using (Stream stm = File.Create(file)) encoder.Save(stm);

                var x1 = (int)EleList.Min(a => a.LocX);
                var x2 = (int)EleList.Max(a => a.LocX + a.SizeWidth);
                var y1 = (int)EleList.Min(a => a.LocY);
                var y2 = (int)EleList.Max(a => a.LocY + a.SizeHeight);

                var rtvalid = new System.Drawing.Rectangle(x1, y1, x2 - x1 + 1, y2 - y1 + 1);
                var img = System.Drawing.Image.FromFile(file) as System.Drawing.Bitmap;
                rstmap = new System.Drawing.Bitmap(rtvalid.Width, rtvalid.Height);
                var g = System.Drawing.Graphics.FromImage(rstmap);
                g.Clear(System.Drawing.Color.Transparent);
                g.DrawImage(img, new System.Drawing.Rectangle(0, 0, rtvalid.Width, rtvalid.Height), rtvalid, System.Drawing.GraphicsUnit.Pixel);
                g.Dispose();
                img.Dispose();
                //mapnew.Save(file);

                return rstmap;
            }
            catch (Exception)
            {
                return rstmap;
            }
            finally
            {

                ImgScaleX = ImgScaleX_old;
                ImgScaleY = ImgScaleY_old;
                ImgMoveX = ImgMoveX_old;
                ImgMoveY = ImgMoveY_old;
            }
        }

        private System.Drawing.Bitmap ResizeMap(System.Drawing.Bitmap map, int resizeWidth)
        {
            var wd = resizeWidth;
            var ht = (int)Math.Round(map.Height / (double)map.Width * resizeWidth);
            return ResizeMap(map, resizeWidth, ht);
        }

        private System.Drawing.Bitmap ResizeMap(System.Drawing.Bitmap map, int resizeWidth, int resizeHeight)
        {
            var wd = resizeWidth;
            var ht = resizeHeight;
            var maprst = new System.Drawing.Bitmap(wd, ht);
            var g = System.Drawing.Graphics.FromImage(maprst);
            g.DrawImage(map, new System.Drawing.Rectangle(0, 0, maprst.Width, maprst.Height), new System.Drawing.RectangleF(0, 0, map.Width, map.Height), System.Drawing.GraphicsUnit.Pixel);
            g.Dispose();
            return maprst;
        }

        private void doDeleteCommand()
        {
            //批量选中的元素
            shadow_todrags.Clear();
            foreach (FrameworkElement fe in cvDrawMain.Children)
            {
                var feinfo = (fe.DataContext as DrawEleInfo);
                if (feinfo == null) continue;
                if (!feinfo.IsSlt) continue;
                shadow_todrags.Add(fe);
            }

            //删除选中元素 
            foreach (var shadow_todrag in shadow_todrags)
            {
                var eleinfo = shadow_todrag.DataContext as DrawEleInfo;
                delItem(eleinfo);
            }
        }

        private void doCopyCommand()
        {
            //批量选中的元素
            shadow_todrags.Clear();
            foreach (FrameworkElement fe in cvDrawMain.Children)
            {
                var feinfo = (fe.DataContext as DrawEleInfo);
                if (feinfo == null) continue;
                if (!feinfo.IsSlt) continue;
                shadow_todrags.Add(fe);
            }

            //已选中项目取消选中状态
            foreach (var ele in shadow_todrags) (ele.DataContext as DrawEleInfo).IsSlt = false;

            //复制选中元素 
            foreach (var shadow_todrag in shadow_todrags)
            {
                //复制元素
                var eleinfo = shadow_todrag.DataContext as DrawEleInfo;
                eleinfo = eleinfo.Clone() as DrawEleInfo;
                //适当错位
                var offset_x = 50;
                var offset_y = 50;
                eleinfo.LocX += offset_x;
                eleinfo.LocY += offset_y;
                if (eleinfo.DrawCommand == DrawCommand.曲线
                    || eleinfo.DrawCommand == DrawCommand.直线)
                {
                    eleinfo.LocX2 += offset_x;
                    eleinfo.LocY2 += offset_y;
                }
                if (eleinfo.DrawCommand == DrawCommand.曲线)
                {
                    eleinfo.Control_1_X += offset_x;
                    eleinfo.Control_1_Y += offset_y;
                }

                //默认选中新图像
                eleinfo.IsSlt = true;

                doAddDrawEleControl(eleinfo);
            }
        }

        private void delItem(DrawEleInfo ele)
        {
            List<FrameworkElement> eleToDel = new List<FrameworkElement>();
            foreach (FrameworkElement fe in cvDrawMain.Children)
            {
                if (fe.DataContext == ele)
                {
                    eleToDel.Add(fe);
                }
            }
            foreach (var e in eleToDel) cvDrawMain.Children.Remove(e);
            EleList.Remove(ele);
            ResetRowHeader();
        }
         
        private bool ColorSelector(out SolidColorBrush rstbrush)
        {
            rstbrush = Brushes.Black;

            var colorDialog = new System.Windows.Forms.ColorDialog();
            colorDialog.AllowFullOpen = true;
            if (colorDialog.ShowDialog() != System.Windows.Forms.DialogResult.OK) return false;

            System.Windows.Media.SolidColorBrush scb = new System.Windows.Media.SolidColorBrush();
            System.Windows.Media.Color color = new System.Windows.Media.Color();
            color.A = colorDialog.Color.A;
            color.B = colorDialog.Color.B;
            color.G = colorDialog.Color.G;
            color.R = colorDialog.Color.R;
            scb.Color = color;

            rstbrush = scb;
            return true;

        }

        private void ResetRowHeader()
        {
            if (EleList == null) return;
            for (int i = 0; i < EleList.Count; i++)
            {
                var row = (DataGridRow)dg1.ItemContainerGenerator.ContainerFromItem(EleList[i]);
                if (row == null) continue;
                row.Header = i + 1;
            }
        }

        #endregion
         

        public event PropertyChangedEventHandler PropertyChanged;
        public void cc(string name)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
        }


    }
    public enum DrawCommand
    {
        无, 直线, 曲线, 矩形, 圆形, 文字, 拖动, 缩放, 复制, 删除, 选择
    }
}
